﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Web.Security;
using Library.Bll;
using Library.Common;
using System.Text;

using HanhuaMicroCredit.BLL;
namespace HanhuaMicroCredit.Admin.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index()
        {
            //if (Current.IsAuthorizedUser())
            //{
            //    return RedirectToAction("index", "home");
            //}
            //else {
            //    if (UIdentity.Instance.IsAuthenticated) {
            //        return RedirectToAction("index", "home");
            //    }
            //}
            return View();
        }

        [HttpPost]
        public ContentResult Index(FormCollection fc)
        {
            string userName = fc["username"].Trim();
            string userPass = fc["password"].Trim();
            userPass = FormsAuthentication.HashPasswordForStoringInConfigFile(userPass, "MD5");
            //
            List<ConditionInfo> l = new List<ConditionInfo>(){
                new ConditionInfo("UserName",CompareType.Equals,userName),
                new ConditionInfo("PassWord",CompareType.Equals,userPass)
            };
            Dictionary<string, object> d = CommonBLL.GetModel("Sys_IBUsers", "*", l);
            //
            if (d != null)
            {
                string IsValid = d.ContainsKey("IsValid") ? d["IsValid"].ToString() : "";
                if (Convert.ToBoolean(IsValid))
                {
                    Users u = new Users(userName, userPass);
                    u._session = false;
                    u._cookie = true;
                    u.d = d;
                    int days = Utils.StrToInt(fc["days"], 0);
                    if (u._cookie)
                        u._saveday = days;//cookie保存一周
                    u.UserLogin();
                    //登录日志
                    UserLog.InsUserLog();
                    InsLogBll.InsertLog("系统登录", "登录", "用户" + userName + "登录成功!");
                    string url = "/Home/";
                    string getReturnUrl = MyRequest.GetQueryString("returnUrl");
                    if (getReturnUrl != "")
                        url = getReturnUrl;
                    return Content(JUIResult.ResultLoginUrl(url));                       
                    
                }
                else
                {
                    return Content(JUIResult.ResultMsg("用户已禁用，请重试"));
                    //return Redirect("/login");
                }
            }
            return Content(JUIResult.ResultMsg("密码或用户名不正确，请重试"));
            //return Redirect("/login");
        }


        public ActionResult LoginOut()
        {
            return View();
        }
    }
}
